//
//  WFCUFCircleVC.m
//  WFChatUIKit
//
//  Created by 0000 on 2024/5/22.
//  Copyright © 2024 Tom Lee. All rights reserved.
//

#import "WFCUFCircleVC.h"
//#import <WebKit/WebKit.h>
//#import "WKWebViewJavascriptBridge.h"
#import "YGExtendChain.h"
#import "SDAutoLayout.h"
#import "WFCUImage.h"

#import "AFNetworking.h"
#import <WFChatClient/WFCChatClient.h>
#import "WFCUPostDynamicVC.h"

#import <ZLPhotoBrowser/ZLPhotoBrowser-Swift.h>
#import <Photos/Photos.h>
#import "MBProgressHUD.h"
#import "UIView+Toast.h"
#import "WFCUConfigManager.h"
#import <Photos/Photos.h>


#import "MomentCell.h"
#import "Moment.h"
#import "Comment.h"
#import "SHPublishViewController.h"
#import "XJJRefresh.h"
#import "MJRefresh.h"
#import "SHFriendHeadView.h"
#import "UIView+Geometry.h"
#import "SDWebImage/UIImageView+WebCache.h"
#import "CLInputToolbar.h"
#import "WFCUFCircleDetailVC.h"
#import "WFCUFCircleMsgListVC.h"
#import "WFCUProfileTableViewController.h"
#import <SDWebImage/SDWebImageManager.h>
#import <SDWebImage/SDWebImageOperation.h>
#import <SDWebImage/SDWebImageDownloader.h>

#define kStatusBarH ([[UIApplication sharedApplication] statusBarFrame].size.height)
//背景自己
#define kActionSheet_BackGroup_Me_Tag 1
//背景其他人
#define kActionSheet_BackGroup_Other_Tag 2

//当前用户
#define UserName @"Alan"

@interface WFCUFCircleVC ()<UITableViewDataSource, UITableViewDelegate,MomentCellDelegate,SHFriendHeadViewDelegate>
{
    id <SDWebImageOperation> _webImageOperation;

}
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *dataArray;
@property (nonatomic, strong)NSMutableArray *photos;
 

@property (nonatomic, strong)UIView * popView ;

//@property(nonatomic, strong)WKWebView *webview;
//
//@property (nonatomic, strong) WVJBResponseCallback callback;
//
//@property WKWebViewJavascriptBridge* bridge;

@property (nonatomic,strong) SHFriendHeadView *tableHeadView;
//@property (nonatomic,strong) UIImageView *coverImageView;
//@property (nonatomic,strong) UIImageView *headImageView;

@property (nonatomic,strong) WFCCUserInfo *me;



@property (nonatomic,strong) UIView *barBackgroundView;
@property (nonatomic, strong) CLInputToolbar *inputToolbar;

@property (nonatomic, strong)NSDictionary *data;


@property (nonatomic, strong)id obj;


@end

@implementation WFCUFCircleVC



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

//    self.navigationController.navigationBar.hidden = YES;
    NSMutableArray *barSubviews = [NSMutableArray array];
    //将导航栏的子控件添加到数组当中,取首个子控件设置透明度(防止导航栏上存在非导航栏自带的控件)
    for (UIView * view in self.navigationController.navigationBar.subviews) {
        if(![view isMemberOfClass:[UIView class]]){
            [barSubviews addObject:view];
        }
    }
    if (!self.barBackgroundView) {
         
        UIView *barBackgroundView = [barSubviews firstObject];
        barBackgroundView.alpha   = 0.;
        self.barBackgroundView = barBackgroundView;
    }
 
//    UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithImage:[WFCUImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(onBackBtn:)];
//    self.navigationController.navigationItem.backBarButtonItem = back;
    [self.navigationController.navigationItem.backBarButtonItem setImage:[WFCUImage imageNamed:@"back_white"]];
    
    UIBarButtonItem *barck = self.navigationController.navigationItem.backBarButtonItem;
    [barck setImage:[UIImage imageNamed:@"back_white"]] ;
    NSLog(@"barck %@ ",barck ) ;
    
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

 
    self.barBackgroundView.alpha   = 1.;
    [self.view endEditing:YES];
    
}


- (void)onBackBtn:(UIButton *)completion {
    
    [self.navigationController popViewControllerAnimated:YES];

}

- (void)onCircleBtn:(UIButton *)completion {
    
      WFCUPostDynamicVC *vc = [[WFCUPostDynamicVC alloc]init];

    [self.navigationController pushViewController:vc animated:YES];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    WEAKSELF_ZM
    UIButton *btn1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 50, 48)];
    
    btn1.sh_chain_extend.image([[UIImage imageNamed:@"circle_rel"] imageWithChangeColor:[UIColor blackColor]]);
 
    [btn1 jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        [weakSelf postDynamic];
    }];
    [btn1 jk_addLongBeganPressActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        [weakSelf onCircleBtn:nil];
    }];
     
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"circle_rel"] style:UIBarButtonItemStylePlain target:self action:@selector(postDynamic)];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn1];
    

    
  
    //    back_white
    
    self.view.backgroundColor = [WFCUConfigManager globalManager].backgroudColor;

    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    if (@available(iOS 15, *)) {
        self.tableView.sectionHeaderTopPadding = 0;
    }
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    self.tableView.backgroundColor = [UIColor clearColor];
    if ([self.tableView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
        if (@available(iOS 11.0, *)) {
            self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            // Fallback on earlier versions
        }
    }
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.separatorColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1.0];
    self.tableView.separatorInset = UIEdgeInsetsZero;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.tableHeaderView = self.tableHeadView;
    [self.view addSubview:self.tableView];

    
    self.dataArray = @[].mutableCopy;
    self.photos = @[].mutableCopy;
    
    //    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 300)];
    //    header.backgroundColor = [WFCUConfigManager globalManager].naviBackgroudColor;
    //    self.tableView.tableHeaderView = header;
    //    self.tableView.contentInset = UIEdgeInsetsMake(-300, 0, 0, 0);
    //    [self.view addSubview:self.tableView];
    
    //    [WKWebViewJavascriptBridge enableLogging];
    //
    //
    //    self.webview = [[WKWebView alloc] initWithFrame:self.view.bounds];
    //    [self.webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://t.yehuoim.com/#/wx/friendsCircle/index" ]]];
    //    [self.view addSubview:self.webview];
    //
    //
    //    _bridge = [WKWebViewJavascriptBridge bridgeForWebView:self.webview];
    //    [_bridge setWebViewDelegate:self.webview];
    //
    //    NSString *savedToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"WFC_APPSERVER_AUTH_TOKEN"];
    ////    NSUserDefaults *sharedDefaults = [[NSUserDefaults alloc] initWithSuiteName:WFC_SHARE_APP_GROUP_ID];//此处id要与开发者中心创建时一致
    ////    NSString *authToken = [sharedDefaults objectForKey:WFC_SHARE_APPSERVICE_AUTH_TOKEN];
    ////
    //    WEAKSELF_ZM
    //    ///<.head
    //    [_bridge registerHandler:@"getHead" handler:^(id data, WVJBResponseCallback responseCallback) {
    //
    //        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    //        if (savedToken) {
    //            [dic setObject:savedToken forKey:@"authToken"];
    //        }
    //
    ////        UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"authToken = %@",savedToken] preferredStyle:UIAlertControllerStyleAlert];
    ////
    ////        UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    ////
    ////        }];
    ////
    ////        [actionSheet addAction:actionCancel];
    ////
    ////        [weakSelf presentViewController:actionSheet animated:YES completion:nil];
    //
    //
    ////        NSLog(@"responseCallback: %@", data);
    //        responseCallback(dic);
    //     }];
    //    [_bridge registerHandler:@"viewCheckArchivements" handler:^(id data, WVJBResponseCallback responseCallback) {
    //        NSLog(@"responseCallback: %@", data);
    //
    //
    //    }];
    
    self.me = [[WFCCIMService sharedWFCIMService] getUserInfo:[WFCCNetworkService sharedInstance].userId refresh:NO];

 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNetworking) name:@"postMeNetworking" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNoticeList) name:@"postNoticeList" object:nil];


    
    [self setRefresh];
    [self getNetworking];
    [self setTextViewToolbar];
    [self getNoticeList];
    [self loadDatas];

    
    

}
-(void)setTextViewToolbar {
    
    
    self.inputToolbar = [[CLInputToolbar alloc] init];
    self.inputToolbar.textViewMaxLine = 3;
    self.inputToolbar.fontSize = 15;
    self.inputToolbar.placeholder = @"Comments" ;
    WEAKSELF_ZM
 
 
    self.inputToolbar.btnsBlock = ^(UIButton *btn) {
 
    };
    [self.view addSubview:self.inputToolbar];
    
    
}


- (void)postDynamic{
    
//    WFCUPostDynamicVC *vc = [[WFCUPostDynamicVC alloc]init];
//    
//    [self.navigationController pushViewController:vc animated:YES];
    
  
    self.popView.alpha = 0 ;
    [([UIApplication sharedApplication].keyWindow ?: [UIApplication sharedApplication].windows.firstObject) addSubview:self.popView];
    self.popView.sd_layout.spaceToSuperView(UIEdgeInsetsMake(0, 0, 0, 0));

    
    [UIView animateWithDuration:0.15 animations:^{

        self.popView.alpha = 1 ;

    } completion:^(BOOL finished) {
       

    }];
    
    
}

- (void)getNoticeList{
    
    WEAKSELF_ZM
    
    NSString *savedToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"WFC_APPSERVER_AUTH_TOKEN"];
    NSString *userId = [WFCCNetworkService sharedInstance].userId;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    
 
    [manager.requestSerializer setValue:savedToken forHTTPHeaderField:@"authToken"];

//    NSString *url = [NSString stringWithFormat:@"https://d.yehuoim.com/friend-circle/topic/userTopic/%@" , userId];
//    NSString *url = [NSString stringWithFormat:@"https://d.yehuoim.com/friend-circle/topic/noticeList" ];
    NSString *url = [NSString stringWithFormat:@"https://d.yehuoim.com/friend-circle/topic/noticeListCount" ];

    
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
            
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dic = responseObject;
            
            NSLog(@" ret---  %@ ", dic );

            NSDictionary *data = [dic handleNullObjectForKey:@"data"];
            weakSelf.data = data;

 

        }
        
        [weakSelf.tableView reloadData];

        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        if (error) {
             
            NSLog(@" ret---  %@ ", error );

        }
        [weakSelf.tableView end_xjj_refresh];

    }];
}

- (void)getNetworking{
    
    WEAKSELF_ZM
    
    [self.tableHeadView.avatarImageView sd_setImageWithURL:[NSURL URLWithString:self.me.portrait] placeholderImage: [WFCUImage imageNamed:@"PersonalChat"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        NSLog(@"%@ err%@",image,error);
    }];
    self.tableHeadView.userName = self.me.displayName;
    
    
    
    NSString *savedToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"WFC_APPSERVER_AUTH_TOKEN"];
    NSString *userId = [WFCCNetworkService sharedInstance].userId;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    
 
    [manager.requestSerializer setValue:savedToken forHTTPHeaderField:@"authToken"];

//    NSString *url = [NSString stringWithFormat:@"https://d.yehuoim.com/friend-circle/topic/userTopic/%@" , userId];
    NSString *url = [NSString stringWithFormat:@"https://d.yehuoim.com/friend-circle/topic/topicList" ];

    
    [manager GET:url parameters:@{@"userId":userId} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
            
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dic = responseObject;
            
//            NSLog(@" ret---  %@ ", dic );
            weakSelf.obj = dic;
            
            [weakSelf loadDatas];
            
        }

        [weakSelf.tableView end_xjj_refresh];

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        if (error) {
             
            NSLog(@" ret---  %@ ", error );

        }
        [weakSelf.tableView end_xjj_refresh];

    }];
    
    
}

- (void)loadDatas{
    
    
    WEAKSELF_ZM
    
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    
    
    NSArray *rows = @[];

    if (weakSelf.obj) {
        rows  = [weakSelf.obj handleNullObjectForKey:@"rows"];
        NSLog(@"当前更新数据- %ld ",rows.count);
    } else {
        
        if ([ZmGetRedUserDefaults(@"circleList" ) jk_JSONStringWithDictionary]) {
             
            rows = [ZmGetRedUserDefaults(@"circleList" ) jk_JSONStringWithDictionary];
            
            NSLog(@"历史刷新数据- %ld ",rows.count);

        }
    }
    
    NSLog(@" ret---  %@ ", rows );
    
    ZmSaveUserDefaults([rows jk_JSONString], @"circleList");
    
    NSMutableArray * tempArray = [NSMutableArray array];

    for (int i = 0; i<rows.count; i++) {

        NSDictionary *obj1 = rows[i];
        NSDictionary *obj2 = [obj1 handleNullObjectForKey:@"topic"];
//                NSDictionary *obj3 = [NSObject dictionaryWithJsonString:[obj2 handleNullObjectForKey:@"content"]];

        Moment *moment = [[Moment alloc] init];
//                moment.commentList = commentList;
//                moment.praiseNameList = @"胡一菲，唐悠悠，陈美嘉，吕小布，曾小贤，张伟，关谷神奇";
        
        NSArray *likeList = [obj1 handleNullObjectForKey:@"likeList"];
        NSMutableArray * praiseNameList = [NSMutableArray array];

        for (int i = 0; i<likeList.count; i++) {
            
            NSDictionary *praise = likeList[i];

            [praiseNameList addObject:[praise handleNullObjectForKey:@"displayName"]];
            
        }
        moment.praiseNameList = [praiseNameList componentsJoinedByString:@","];
        moment.isLike = [[obj1 handleNullObjectForKey:@"like"] containsString:@"Y"];

        NSArray *replyList = [obj1 handleNullObjectForKey:@"replyList"];
        NSMutableArray * commentList = [NSMutableArray array];
        for (int j = 0; j < replyList.count; j ++) {
            NSDictionary *reply = replyList[j];

            Comment *comment = [[Comment alloc] init];
            comment.userName = [reply handleNullObjectForKey:@"displayName"];
            comment.text = [reply handleNullObjectForKey:@"content"];
            comment.time = [NSObject retWithLongDate:[reply handleNullObjectForKey:@"createTime"]];
            comment.pk = 0;
            comment.replyId = [reply handleNullObjectForKey:@"replyId"];
            [commentList addObject:comment];
        }
        
        NSString *str = [NSString stringWithFormat:@"%@",[obj2 handleNullObjectForKey:@"displayName"]] ;
        moment.commentList = commentList;
        moment.userName = [str length] > 0 ? [obj2 handleNullObjectForKey:@"displayName"] :  str ;
        moment.time = [NSObject retWithLongDate:[obj2 handleNullObjectForKey:@"createTime"]];
        moment.singleWidth = 500;
        moment.singleHeight = 315;
        moment.userThumbPath = [obj2 handleNullObjectForKey:@"portrait"] ;
        moment.topicId = [obj2 handleNullObjectForKey:@"topicId"] ;
        moment.userId = [obj2 handleNullObjectForKey:@"userId"] ;

        moment.topicType = [obj2 handleNullObjectForKey:@"topicType"] ;

        
        NSString *imageStr = [NSString stringWithFormat:@"%@",[obj2 handleNullObjectForKey:@"location"]];
        if (imageStr.length > 1) {
             
            moment.imageFArr = [[obj2 handleNullObjectForKey:@"location"] componentsSeparatedByString:@","].mutableCopy  ;

        }else{
            moment.imageFArr = @[].mutableCopy;
        }
        moment.text = [obj2 handleNullObjectForKey:@"content"];
        if (moment.imageFArr.count) {
            moment.fileCount = moment.imageFArr.count;
        }
        
        if ([moment.topicType containsString:@"VIDEO"]) {
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                 NSUserDomainMask, YES);
            NSString *documentDirectory = [paths objectAtIndex:0];
            
            NSURL *url = [NSURL URLWithString:[moment.imageFArr firstObject]];
            NSString *desFileName = [documentDirectory stringByAppendingPathComponent:[[url lastPathComponent] stringByDeletingPathExtension]];
            
            UIImage *img1 = [UIImage imageWithContentsOfFile:desFileName];
            
            if (!img1) {
                WEAKSELF_ZM
                // 异步下载图片
                dispatch_queue_t downloadQueue = dispatch_queue_create("com.example.downloadQueue", DISPATCH_QUEUE_CONCURRENT);
                dispatch_group_t group = dispatch_group_create();
                dispatch_group_async( group,  downloadQueue, ^{
                    // 回到主线程更新UI
                   
                    UIImage *loc = [weakSelf getVideoThumbnailWithUrl:url second:1];
                    if (loc) {
                         
                        [UIImageJPEGRepresentation(loc, 0.6) writeToFile:desFileName atomically:YES];
                        NSLog(@"保存下载数据");
                    }
                    dispatch_async(dispatch_get_main_queue(), ^{
                      
//                        UIImage *loc = [weakSelf getVideoThumbnailWithUrl:url second:1];
//                        [UIImageJPEGRepresentation(loc, 0.6) writeToFile:desFileName atomically:YES];
                        [weakSelf.tableView reloadData];
                        NSLog(@"刷新下载数据");
                    });
                });
                
            }
        }else{
            for (int i = 0; i<moment.imageFArr.count; i++) {
                
                @try {
                    NSURL *imgurl = [NSURL URLWithString:[moment.imageFArr[i] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

                    NSString *path = [documentDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", [imgurl lastPathComponent]]];

                    NSFileManager *fileManager = [NSFileManager defaultManager];
                    if ([fileManager fileExistsAtPath:path]==NO) {

                        
                        
                        SDWebImageManager *manager = [SDWebImageManager sharedManager];
                        _webImageOperation = [manager loadImageWithURL:imgurl options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
                            if (expectedSize > 0) {
                             }
                        } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
                            if (error) {
                                NSLog(@"SDWebImage failed to download image: %@", error);
                            }
//                            NSLog(@"下载图片 %@ ",image);
                            NSLog(@"刷新下载数据");
 
                            if (image) {
                                 
                                NSString *path1 = [documentDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", [imageURL lastPathComponent]]];

                                NSLog(@"下载图片 %@   ",path1);

                                NSData *imgData = UIImageJPEGRepresentation(image, 0.65);
        //
        //
                                if([imgData writeToFile:path1 atomically:YES]) {
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        [weakSelf.tableView reloadData];
                                    });
                                }
                            }
                           

    //                        _webImageOperation = nil;
    //                        if (image) {
    //
    //                            imageView.image = image;
    //
    //                        };
        //                        dispatch_async(dispatch_get_main_queue(), ^{
        //                            [self imageLoadingComplete];
        //                        });
                        }];
                        
                        
                    }

                    
                 
                NSLog(@"%@",_webImageOperation);
                } @catch (NSException *e) {
    //                    MWLog(@"Photo from web: %@", e);
//                    _webImageOperation = nil;
    //                    [self imageLoadingComplete];
                }
            }
            
        }
       
        
        moment.isDelete = ![weakSelf.me.userId containsString:[obj2 handleNullObjectForKey:@"userId"]];
        
        [tempArray addObject:moment];
        
    }
    weakSelf.dataArray = tempArray ;
    
    [weakSelf.tableView reloadData];

        
}

//这本来是个异步调用，但写成这种方便大家看和复制来直接测试
- (UIImage*)getVideoThumbnailWithUrl:(NSURL*)videoUrl second:(CGFloat)second
{
    if (!videoUrl)
    {
        NSLog(@"WARNING:videoUrl为空");
        return nil;
    }
    AVURLAsset *urlSet = [AVURLAsset assetWithURL:videoUrl];
    AVAssetImageGenerator *imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlSet];
    imageGenerator.appliesPreferredTrackTransform = YES;
    imageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    
    /*
     如果不需要获取缩略图，就设置为NO，如果需要获取缩略图，则maximumSize为获取的最大尺寸。
     以BBC为例，getThumbnail = NO时，打印宽高数据为：1920*1072。
     getThumbnail = YES时，maximumSize为100*100。打印宽高数据为：100*55.
     注：不乘[UIScreen mainScreen].scale，会发现缩略图在100*100很虚。
     */
    BOOL getThumbnail = YES;
    if (getThumbnail)
    {
        CGFloat width = [UIScreen mainScreen].scale * ZmScreenWidth_N();
        imageGenerator.maximumSize =  CGSizeMake(width, width);
    }
    NSError *error = nil;
    CMTime time = CMTimeMake(second,1);
    CMTime actucalTime;
    CGImageRef cgImage = [imageGenerator copyCGImageAtTime:time actualTime:&actucalTime error:&error];
    if (error) {
        NSLog(@"ERROR:获取视频图片失败,%@",error.domain);
    }
    CMTimeShow(actucalTime);
    UIImage *image = [UIImage imageWithCGImage:cgImage];
    NSLog(@"imageWidth=%f,imageHeight=%f",image.size.width,image.size.height);
    CGImageRelease(cgImage);
    
    
    return image;
}


#pragma mark - Table view data source
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    return self.dataArray.count ;
//}


#pragma mark - 配置刷新、加载
- (void)setRefresh{
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self getNetworking];
        });
    }];
    
    UIImageView *refreshView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    refreshView.image = [UIImage imageNamed:@"moment_refresh"];
    
    XJJHolyCrazyHeader *crazyRefresh = [XJJHolyCrazyHeader holyCrazyCustomHeaderWithCustomContentView:refreshView];
    crazyRefresh.startPosition = CGPointMake(20, -30-10 );
//    crazyRefresh.startPosition = CGPointMake(20, 32);
    crazyRefresh.refreshingPosition = CGPointMake(20,ZmNavigationHeight_N());
    
    __weak typeof(self) weakSelf = self;
    [self.tableView add_xjj_refreshHeader:crazyRefresh refreshBlock:^{
        
        [weakSelf.tableView setRefreshState:XJJRefreshStateIdle];
        
        [weakSelf.tableView replace_xjj_refreshBlock:^{
            
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf getNetworking];
//            });
        }];
    }];
}

#pragma mark - 刷新数据
- (void)loadNewData{
    NSLog(@"刷新数据");

//    NSMutableArray *temp = [self getFriendDataWithNum:3];
//
//    for (Moment *model in temp) {
//        [self.dataArray insertObject:model atIndex:0];
//    }
//
//    [self.tableView reloadData];
//
//    [self.tableView end_xjj_refresh];
}

#pragma mark - 加载数据
- (void)loadOldData{
    NSLog(@"加载数据");

//    NSArray *temp = [self getFriendDataWithNum:3];
//
//    for (Moment *model in temp) {
//
//        [self.dataArray addObject:model];
//    }
//
//    [self.tableView reloadData];
//
//    //滚动到指定位置
//    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataArray.count - temp.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
//
//    [self.tableView.mj_footer endRefreshing];
}


#pragma mark - Getter
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight) style:UITableViewStylePlain];

//        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -(44 + kStatusBarH), kWidth, kHeight) style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        _tableView.separatorColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1.0];
        _tableView.separatorInset = UIEdgeInsetsZero;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.tableHeaderView = self.tableHeadView;
    }
    return _tableView;
}

- (SHFriendHeadView *)tableHeadView
{
    if (!_tableHeadView) {
        
        CGFloat wsf =  ZmScreenWidth_N()   ;
        CGFloat ws1 = wsf  / 360 * 282;
        
        _tableHeadView = [[SHFriendHeadView alloc] initWithFrame:CGRectMake(0, 0, kWidth, ws1)];
        _tableHeadView.backgroundColor = [UIColor whiteColor];
        _tableHeadView.userInteractionEnabled = YES;
//        [_tableHeadView addSubview:self.coverImageView];
//        [_tableHeadView addSubview:self.headImageView];
        _tableHeadView.userName = self.me.displayName;
//        _tableHeadView.userAvatar = [self.me.portrait stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        _tableHeadView.backgroundUrl = [NSString stringWithFormat:@"%@",@"circle_head"];
         
        
        _tableHeadView.delegate = self;
    }
    return _tableHeadView;
}
//
//- (UIImageView *)coverImageView
//{
//    if (!_coverImageView) {
//        
//        CGFloat wsf =  ZmScreenWidth_N()   ;
//        CGFloat ws1 = wsf  / 360 * 282;
//        
//     
//        
//        _coverImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ZmScreenWidth_N(), ws1)];
//        _coverImageView.backgroundColor = [UIColor clearColor];
//        _coverImageView.contentMode = UIViewContentModeScaleAspectFill;
//        _coverImageView.contentScaleFactor = [[UIScreen mainScreen] scale];
//        _coverImageView.clipsToBounds = YES;
//        _coverImageView.userInteractionEnabled = YES;
//        _coverImageView.image = [UIImage imageNamed:@"circle_head"];
//    }
//    return _coverImageView;
//}
//
//- (UIImageView *)headImageView
//{
//    if (!_headImageView) {
//        _headImageView = [[UIImageView alloc] initWithFrame:CGRectMake(kWidth-85, self.coverImageView.bottom-40, 64, 64)];
//        _headImageView.backgroundColor = [UIColor clearColor];
//        _headImageView.layer.borderColor = [[UIColor whiteColor] CGColor];
//        _headImageView.layer.borderWidth = 2;
//        _headImageView.userInteractionEnabled = YES;
//        _headImageView.contentMode = UIViewContentModeScaleAspectFill;
//        _headImageView.image = [UIImage imageNamed:@"moment_head"];
//    }
//    return _headImageView;
//}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
 
#pragma mark - MomentCellDelegate
// 点击用户头像
- (void)didClickHead:(MomentCell *)cell
{
    NSLog(@"击用户头像");
    
    WFCUProfileTableViewController *vc = [[WFCUProfileTableViewController alloc] init];
    vc.userId = cell.moment.userId;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
    
}
// 赞
- (void)didLikeMoment:(MomentCell *)cell
{
    NSLog(@"点击了====菜单");
    
    __block BOOL isLike = NO;
    
    NSInteger index = [self.dataArray indexOfObject:cell.moment];
    
    //查看点赞列表是否有自己
    if ([cell.moment.praiseNameList containsString:self.me.displayName]) {
        isLike = YES;
    }
    //    __weak typeof(self) weakSelf = self;
    NSMutableString *muString = [NSMutableString string];
    if(cell.moment.praiseNameList.length > 0) {
        [muString appendString:cell.moment.praiseNameList];
    }
    
  
    
    
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = @"加载中...";
    [hud showAnimated:YES];
//    /topic/sendTopic
    
    NSString *authToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"WFC_APPSERVER_AUTH_TOKEN"];
    NSString *userId = [WFCCNetworkService sharedInstance].userId;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    
    //在调用其他接口时需要把cookie传给后台，也就是设置cookie的过程

    if(authToken.length) {
        [manager.requestSerializer setValue:authToken forHTTPHeaderField:@"authToken"];
 
    }
 
    
    WEAKSELF_ZM
    NSDictionary *parameters = @{@"topicId":cell.moment.topicId  }; ///<.TEXT, IMAGE, VIDEO
   
    NSString *url = isLike ? [NSString stringWithFormat:@"https://d.yehuoim.com/friend-circle/topic/cancelLike/%@" , cell.moment.topicId] : [NSString stringWithFormat:@"https://d.yehuoim.com/friend-circle/topic/like/%@" , cell.moment.topicId];
//    {\"text\":\"文字内容\",\"imgList\":[\"http://111\",\"http://222\"],\"videoList\":[\"http:111\",\"http://222\"]}")
    [manager GET:url
       parameters:parameters
         progress:nil
          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [hud hideAnimated:YES];
            NSDictionary *dic = responseObject;
            NSLog(@" ret---  %@ ", dic );

            if([dic[@"code"] intValue] == 200) {
                
     
                
                if (isLike) {//点过赞了
                    NSRange range1 = [cell.moment.praiseNameList rangeOfString:[@"," stringByAppendingString:weakSelf.me.displayName]];
                    NSRange range2 = [cell.moment.praiseNameList rangeOfString:weakSelf.me.displayName];
                    if(range1.length) {
                        cell.moment.praiseNameList = [muString substringToIndex:range1.location];
                    } else if(range2.length) {
                        cell.moment.praiseNameList = [muString substringToIndex:range2.location];
                    }
                    cell.moment.isLike = NO;

                }else{
                    cell.moment.isLike = YES;
                    if([cell.moment.praiseNameList isEqualToString:@""] || (cell.moment.praiseNameList == nil)){
                        cell.moment.praiseNameList = [muString stringByAppendingString:weakSelf.me.displayName];
                    } else {
                        cell.moment.praiseNameList = [muString stringByAppendingString:[@"," stringByAppendingString:weakSelf.me.displayName]];
                    }
                     
                }
                
                [weakSelf.dataArray replaceObjectAtIndex:index withObject:cell.moment];
                //进行刷新
                [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
              
                
                
                
            }else{
                
                
            }
 
            
            
        });
 
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (error) {
            
            NSLog(@" ret---  %@ ", error );
            
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [hud hideAnimated:YES];

            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.mode = MBProgressHUDModeText;
            hud.label.text = error.localizedDescription;
            //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
            [hud hideAnimated:YES afterDelay:1.f];
        });
        
    }];
    
    
    
    
    
}
// 评论
- (void)didAddComment:(MomentCell *)cell
{
    NSLog(@"评论");
    
    NSInteger index = [self.dataArray indexOfObject:cell.moment];

    WEAKSELF_ZM
    [self.inputToolbar inputToolbarSendText:^(NSString *text) {

        
        
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.label.text = @"加载中...";
        [hud showAnimated:YES];
    //    /topic/sendTopic
        
        NSString *authToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"WFC_APPSERVER_AUTH_TOKEN"];
//        NSString *userId = [WFCCNetworkService sharedInstance].userId;
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
        
        //在调用其他接口时需要把cookie传给后台，也就是设置cookie的过程

        if(authToken.length) {
            [manager.requestSerializer setValue:authToken forHTTPHeaderField:@"authToken"];
     
        }
     
        
        WEAKSELF_ZM
        NSDictionary *parameters = @{ @"content":text ,@"replyId":cell.moment.topicId,@"replyType":@"1" }; ///<.TEXT, IMAGE, VIDEO
     
        NSString *url = [NSString stringWithFormat:@"https://d.yehuoim.com/friend-circle/topic/reply"  ];
    //    {\"text\":\"文字内容\",\"imgList\":[\"http://111\",\"http://222\"],\"videoList\":[\"http:111\",\"http://222\"]}")
        [manager POST:url
           parameters:parameters
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            
            dispatch_async(dispatch_get_main_queue(), ^{
                

                NSDictionary *dic = responseObject;
                [hud hideAnimated:YES];
                NSLog(@" ret---  %@ ", dic );

                if([responseObject[@"code"] intValue] == 200) {
                    
                    NSDictionary *obj = [dic handleNullObjectForKey:@"data"];
                    
                    
                    NSMutableArray *reply = cell.moment.commentList.mutableCopy;
                    
                    Comment *comment = [[Comment alloc] init];
                    comment.userName = [obj handleNullObjectForKey:@"displayName"];
                    comment.text = [obj handleNullObjectForKey:@"content"];
                    comment.time = [NSObject retWithLongDate:[obj handleNullObjectForKey:@"createTime"]];
                    comment.pk = 0;
                    comment.replyId = [obj handleNullObjectForKey:@"replyId"];
                    [reply addObject:comment];
                    
                    
                    cell.moment.commentList = reply;
 

                    [weakSelf.dataArray replaceObjectAtIndex:index withObject:cell.moment];
                    //进行刷新
                    [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
                  
                    
                    
                    
                }else{
                    
                    
                }
     
                
                
            });
     
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            if (error) {
                
                NSLog(@" ret---  %@ ", error );
                
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [hud hideAnimated:YES];

                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.mode = MBProgressHUDModeText;
                hud.label.text = error.localizedDescription;
                //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
                [hud hideAnimated:YES afterDelay:1.f];
            });
            
        }];
        
        
        
    }];
    [self.inputToolbar popToolbar];
}
 


// 查看全文/收起
- (void)didSelectFullText:(MomentCell *)cell
{
    NSLog(@"全文/收起");
    
    [self.tableView reloadData];
}
// 删除
- (void)didDeleteMoment:(MomentCell *)cell
{
    NSLog(@"删除");
    
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = @"加载中...";
    [hud showAnimated:YES];
//    /topic/sendTopic
    
    NSString *authToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"WFC_APPSERVER_AUTH_TOKEN"];
    NSString *userId = [WFCCNetworkService sharedInstance].userId;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    
    //在调用其他接口时需要把cookie传给后台，也就是设置cookie的过程

    if(authToken.length) {
        [manager.requestSerializer setValue:authToken forHTTPHeaderField:@"authToken"];
 
    }
 
    
    WEAKSELF_ZM
    NSDictionary *parameters = @{@"topicId":cell.moment.topicId  }; ///<.TEXT, IMAGE, VIDEO
 
    NSString *url = [NSString stringWithFormat:@"https://d.yehuoim.com/friend-circle/topic/removeTopic/%@" , cell.moment.topicId];
//    {\"text\":\"文字内容\",\"imgList\":[\"http://111\",\"http://222\"],\"videoList\":[\"http:111\",\"http://222\"]}")
    [manager GET:url
       parameters:parameters
         progress:nil
          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [hud hideAnimated:YES];
            NSDictionary *dic = responseObject;
            NSLog(@" ret---  %@ ", dic );

            if([dic[@"code"] intValue] == 200) {
                
            
                NSInteger index = cell.tag;
                //数组中移除
                [weakSelf.dataArray removeObjectAtIndex:index];
                //刷新表格
                [weakSelf.tableView reloadData];
                
                
            }else{
                
                
            }
 
            
            
        });
 
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (error) {
            
            NSLog(@" ret---  %@ ", error );
            
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [hud hideAnimated:YES];

            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.mode = MBProgressHUDModeText;
            hud.label.text = error.localizedDescription;
            //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
            [hud hideAnimated:YES afterDelay:1.f];
        });
        
    }];
    
    
    
    
}
// 选择评论
- (void)didSelectComment:(Comment *)comment
{
    NSLog(@"点击评论");
}
// 点击高亮文字
- (void)didClickLink:(MLLink *)link linkText:(NSString *)linkText momentCell:(MomentCell *)cell
{
    if(link.linkType == MLLinkTypeURL) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:linkText]];
    } else if(link.linkType == MLLinkTypeEmail) {
        NSString *recipients = @"mailto:cheerylau@126.com";
        NSString *email = [NSString stringWithFormat:@"%@", recipients];
        email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
    } else if(link.linkType == MLLinkTypePhoneNumber) {
        NSString *mobileNumber = [NSString stringWithFormat:@"tel://%@", linkText];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:mobileNumber]];
    }
    NSLog(@"点击高亮文字：%@",linkText);
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"MomentCell";
    MomentCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[MomentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor whiteColor];
    }
    cell.tag = indexPath.row;
    cell.moment = [self.dataArray objectAtIndex:indexPath.row];
    cell.delegate = self;
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = [MomentCell momentCellHeightForMoment:[self.dataArray objectAtIndex:indexPath.row]];
    return height;
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    switch (actionSheet.tag) {
        case kActionSheet_BackGroup_Me_Tag://自己背景
        {
            switch (buttonIndex) {
                case 0://相册
                {
                    NSLog(@"点击了==相册");
                }
                    break;
                case 1://相机
                {
                    NSLog(@"点击了==相机");
                }
                    
                default:
                    break;
            }
        }
            break;
        case kActionSheet_BackGroup_Other_Tag://别人背景
        {
            switch (buttonIndex) {
                case 0://保存到相册
                {
                    NSLog(@"点击了==保存到相册");
                }
                    break;
                default:
                    break;
            }
        }
            
            break;
        default:
            break;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        if ([[self.data handleNullObjectForKey:@"count"] intValue] > 0) {
             
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
            view.backgroundColor = [UIColor whiteColor];
            
            
            UIView *view1 = [[UIView alloc]init];
            [view addSubview:view1];

            view1.sd_layout.centerXEqualToView(view).heightIs(40).centerYEqualToView(view);
            view1.sh_chain_extend.roundSize(10).backgroundColor([UIColor colorWithHexExtendString:@"#575757"]).clipsToBounds(YES);
            
             
            UIImageView *headImageView = [[UIImageView alloc] init ];
            [view1 addSubview:headImageView];
             
            headImageView.sd_layout.leftSpaceToView(view1, 6).centerYEqualToView(view1).widthIs(30).heightIs(30);
            
            UILabel *nameLab = [[UILabel alloc] init ];
           
            [view1 addSubview:nameLab];
            
            nameLab.sd_layout.leftSpaceToView(headImageView, 10).autoHeightRatio(0).centerYEqualToView(view1);
            [nameLab setSingleLineAutoResizeWithMaxWidth:ZmScreenWidth_N()/2];
            
            nameLab.sh_chain_extend.titleColorWhite().font_size(16).title([NSString stringWithFormat:@"%@条新消息",[self.data handleNullObjectForKey:@"count"] ]);
            
            [view1 setupAutoWidthWithRightView:nameLab rightMargin:15 ];
            
 
            [headImageView sd_setImageWithURL:[NSURL URLWithString:[self.data handleNullObjectForKey:@"portrait"]] placeholderImage:[WFCUImage imageNamed:@"PersonalChat"]];

            WEAKSELF_ZM
            [view jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
                 
                WFCUFCircleMsgListVC *vc = [[WFCUFCircleMsgListVC alloc]init];
                
//                vc.dataArray = weakSelf.noticeList.mutableCopy;
                [weakSelf.navigationController pushViewController:vc animated:YES];
                
            }];
            
            return view;
        }
      
    }
    
    return nil;

    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return [[self.data handleNullObjectForKey:@"count"] intValue] > 0 ? 50 : 0;
    } else {
        return 0;
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
   
    WFCUFCircleDetailVC *vc = [[WFCUFCircleDetailVC alloc]init];
    
    vc.dataArray = @[[self.dataArray objectAtIndex:indexPath.row]].mutableCopy;
    [self.navigationController pushViewController:vc animated:YES];
    
    
}
#pragma mark - UITableViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//    NSIndexPath *indexPath =  [self.tableView indexPathForRowAtPoint:CGPointMake(scrollView.contentOffset.x, scrollView.contentOffset.y)];
//    MomentCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
//    cell.menuView.show = NO;
    
    if (scrollView.contentOffset.y > ZmNavigationHeight_N() + 20){
        self.barBackgroundView.alpha   = 1.;

    }else{
        self.barBackgroundView.alpha   = 0.;

    }
    
    [self.view endEditing:YES];

}

#pragma mark - SHFriendHeadViewDelegate
- (void)headClick:(SHFriendHeadView *)view ClickType:(SHFriendHeadClickType)clickType{
    switch (clickType) {
        case SHFriendHeadClickType_Avatar://头像
        {
            NSLog(@"头部视图===头像点击");
            [self messageUserClick:nil message:UserName];
        }
            break;
        case SHFriendHeadClickType_Background://背景
            NSLog(@"头部视图===背景点击");
        {
//            UIActionSheet *sheet;
//            if ([self.userInfo isEqualToString:UserName]) {//自己
//                
//                sheet = [[UIActionSheet alloc] initWithTitle:@"更换背景" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相册",@"相机", nil];
//                sheet.tag = kActionSheet_BackGroup_Me_Tag;
//                
//            }else{//其他人
//                
//                sheet = [[UIActionSheet alloc] initWithTitle:@"提示" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"保存到相册" otherButtonTitles:nil, nil];
//                sheet.tag = kActionSheet_BackGroup_Other_Tag;
//            }
//            [sheet showInView:self.view];
        }
            break;
        default:
            break;
    }
}

- (void)messageUserClick:(MomentCell *)cell message:(NSString *)message{
    
    //移除点赞
//    [[SHTimeLineMenu shareSHTimeLineMenu] removeFromSuperview];
    
//    UIAlertView *ale = [[UIAlertView alloc]initWithTitle:@"用户点击" message:message delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
//    [ale show];
    
}



- (UIView *)popView{
   if (!_popView) {
       _popView = [[UIView alloc]init];
       
       _popView.sh_chain_extend.backgroundColor([UIColor colorWithHexExtendString:@"#3F3C41" alpha:0.57]).addTarget_action(self, @selector(removeMain));

       UIView *view = [[UIView alloc]init];
       [_popView addSubview:view];
       view.sd_layout.centerXEqualToView(self.view).bottomEqualToView(self.view).offset(30).heightIs(60 * 3 + 60).widthIs(ZmScreenWidth_N()  ) ;
       view.sh_chain_extend.backgroundColorWhite().roundSize(20);

       
       
     
       
//       NSDictionary *attributes = @{
//           NSForegroundColorAttributeName: [UIColor colorWithHexExtendString:@"#797979"],
//           NSFontAttributeName: [UIFont systemFontOfSize:12]
//       };
//       NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:attributes];
       
       NSString *text = @"拍摄\n照片或视频";
       NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text];
       [attributedText setAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:12],
                             NSForegroundColorAttributeName : [UIColor colorWithHexExtendString:@"#797979"]} range:NSMakeRange(2, text.length - 2)];
 
       

       UIButton *btn1 = [[UIButton alloc]init];
       
       [view addSubview:btn1];
       btn1.sh_chain_extend.font_size(16).titleColorBlack().addTarget_action(self, @selector(on1Register));
       btn1.sd_layout.leftSpaceToView(view, 20).heightIs(60).widthIs(ZmScreenWidth_N() - 40).topSpaceToView(view, 10);
       btn1.titleLabel.numberOfLines = 0;
       btn1.titleLabel.isAttributedContent = YES;
       btn1.titleLabel.textAlignment = NSTextAlignmentCenter;
       [btn1 setAttributedTitle:attributedText forState:UIControlStateNormal];

       
       
       UIView *line1 = [[UIView alloc]init];
       line1.backgroundColor = [UIColor colorWithHexExtendString:@"#D8D8D8"];
       [btn1 addSubview:line1];
       line1.sd_layout.leftEqualToView(btn1).bottomEqualToView(btn1).rightEqualToView(btn1).heightIs(1);
       
        
       
       
       
       
       
       
       UIButton *btn2 = [[UIButton alloc]init];
       
       [view addSubview:btn2];
       btn2.sh_chain_extend.title(@"从相册选择").font_size(16).titleColorBlack().addTarget_action(self, @selector(on2Register));
       btn2.sd_layout.leftSpaceToView(view, 20).heightIs(60).widthIs(ZmScreenWidth_N() - 40).topSpaceToView(view, 70);
       
       UIView *line2 = [[UIView alloc]init];
       line2.backgroundColor = [UIColor colorWithHexExtendString:@"#D8D8D8"];
       [btn2 addSubview:line2];
       line2.sd_layout.leftEqualToView(btn2).bottomEqualToView(btn2).rightEqualToView(btn2).heightIs(1);
       
       
       
       
       
       
       
       UIButton *btn3 = [[UIButton alloc]init];
       
       [view addSubview:btn3];
       btn3.sh_chain_extend.title(@"取消").font_size(16).titleColor([UIColor colorWithHexExtendString:@"#016EFF"]);
       btn3.sd_layout.leftSpaceToView(view, 20).heightIs(60).widthIs(ZmScreenWidth_N() - 40).topSpaceToView(btn2, 1);
       
      
//       UIButton *btn1_c = [[UIButton alloc]init];
//       [view addSubview:btn1_c];
//       btn1_c.sd_layout.leftSpaceToView(view, 10).topSpaceToView(view, 20).heightIs(36).widthIs(140);
//       btn1_c.sh_chain_extend.title(@"浅色主题").titleColor([UIColor colorWithHexExtendString:@"#2B2136"]).font_size(17).addTarget_action(self, @selector(on1Register));
//     
//       UIView *lab1 = [[UIView alloc]init];
//       
//       [view addSubview:lab1];
//       lab1.sd_layout.topSpaceToView(btn1_c, 5).leftSpaceToView(view, 5).rightSpaceToView(view, 5).heightIs(1) ;
//
//       lab1.sh_chain_extend.backgroundColorLight();
//       
//       
//       
//       
//       UIButton *btn1_d = [[UIButton alloc]init];
//       [view addSubview:btn1_d];
//       btn1_d.sd_layout.leftSpaceToView(view, 10).topSpaceToView(lab1, 10).heightIs(36).widthIs(140);
//       btn1_d.sh_chain_extend.title(@"深色主题").titleColor([UIColor colorWithHexExtendString:@"#2B2136"]).font_size (17).addTarget_action(self, @selector(on2Register));
       
       
       
       
//       [view setupAutoHeightWithBottomView:btn1_d bottomMargin:20];
       WEAKSELF_ZM
    
        [btn3 jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {


            [weakSelf removeMain];

        }];
       
   }
   return _popView;
}

- (void)checkAndAlertCameraAccessRight {
    AVAuthorizationStatus authStatus =
    [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusDenied ||
        authStatus == AVAuthorizationStatusRestricted) {
        UIAlertView *alertView = [[UIAlertView alloc]
                                  initWithTitle:@"拍照权限"
                                  message:@"需要拍照权限，请在设置里打开"
                                  delegate:nil
                                  cancelButtonTitle:@"确认"
                                  otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }
}
- (void)on1Register  {
   [self removeMain];
    
    WEAKSELF_ZM
    [self checkAndAlertCameraAccessRight];
    
    [ZLPhotoConfiguration default].allowEditVideo = YES;
    ZLCustomCamera *cc = [[ZLCustomCamera alloc] init];
    
    cc.takeDoneBlock = ^(UIImage * _Nullable image, NSURL * _Nullable url) {
        NSLog(@"select the image");
        WFCUPostDynamicVC *vc = [[WFCUPostDynamicVC alloc]init];

        if (image) {
//            [self imageDidCapture:image fullImage:NO];
            
            [weakSelf.photos addObject:image];
            vc.photos = weakSelf.photos;

        } else {
            
            vc.videoUrl = url;
            
            
        }
        
        
 
        [weakSelf.navigationController pushViewController:vc animated:YES];
        
        
    };
    [self showDetailViewController:cc sender:nil];

    
}
- (void)on2Register  {
   [self removeMain];
    
    WEAKSELF_ZM
    self.photos = @[].mutableCopy;
    
    [ZLPhotoConfiguration default].allowSelectImage = YES;
    [ZLPhotoConfiguration default].allowSelectVideo = YES;
    [ZLPhotoConfiguration default].maxSelectCount = 9;
    [ZLPhotoConfiguration default].allowMixSelect = NO;
    [ZLPhotoConfiguration default].allowTakePhotoInLibrary = NO;
    [ZLPhotoConfiguration default].allowEditImage = YES;
    [ZLPhotoConfiguration default].allowEditVideo = YES;
    //视频最大时长，默认是5分钟，可以更改为更大
    [ZLPhotoConfiguration default].maxSelectVideoDuration = 300;
    [ZLPhotoConfiguration default].maxEditVideoTime = 300;
    [ZLPhotoConfiguration default].cameraConfiguration.sessionPreset = CaptureSessionPresetVga640x480;
    [ZLPhotoConfiguration default].cameraConfiguration.videoExportType = VideoExportTypeMp4;
    
    ZLPhotoPreviewSheet *ps = [[ZLPhotoPreviewSheet alloc] initWithSelectedAssets:self.photos ];
    ps.selectImageBlock = ^(NSArray<ZLResultModel *> *models, BOOL isOriginal) {
        NSMutableArray *photos = [[NSMutableArray alloc] init];
        [models enumerateObjectsUsingBlock:^(ZLResultModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [photos addObject:obj.asset];
        }];

        weakSelf.photos = photos;
        
        WFCUPostDynamicVC *vc = [[WFCUPostDynamicVC alloc]init];
        vc.photos = weakSelf.photos;
        
        [weakSelf.navigationController pushViewController:vc animated:YES];
        
//        [weakSelf recursiveHandle:photos isFullImage:isOriginal];
    };
    [ps showPhotoLibraryWithSender:self ];
    
    
}
- (void)removeMain
{


  [UIView animateWithDuration:0.15 animations:^{

      self.popView.alpha = 0 ;
  } completion:^(BOOL finished) {
      self.popView.hidden = YES;
      [self.popView removeFromSuperview];
      self.popView  = nil;

  }];
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
